package org.adorsys.aderp.cash.xchange;

import java.lang.reflect.InvocationTargetException;

import javax.annotation.Resource;

import org.adorsys.aderp.cash.domain.CashReceipt;
import org.adorsys.aderp.cash.service.CashReceiptService;
import org.adorsys.aderp.jpa.api.xchange.DataQuery;
import org.adorsys.aderp.jpa.api.xchange.DataRequest;
import org.adorsys.aderp.jpa.api.xchange.DataResponse;
import org.adorsys.aderp.jpa.api.xchange.DataView;
import org.adorsys.aderp.jpa.api.xchange.ObjectMapper;
import org.adorsys.aderp.jpa.api.xchange.XchangeRecordService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class CashReceiptXChangeRecordService implements XchangeRecordService {

	@Resource
	private CashReceiptService cashReceiptService;

	@Override
	public DataResponse loadEntity(DataRequest dataRequest) {
		DataResponse successResponse = null;
		if (CashReceipt.class.getName().equals(dataRequest.getEntityName())) {
			try {
				successResponse = this.loadOrgaPerson(dataRequest);
			} catch (IllegalAccessException e) {
				return this.getResponseError(e);
			} catch (InvocationTargetException e) {
				return this.getResponseError(e);
			} catch (NoSuchMethodException e) {
				return this.getResponseError(e);
			}catch(Exception e){
				return this.getResponseError(e);
			}
		}

		return successResponse;
	}

	@Override
	public Page<DataResponse> searchEntities(DataQuery dataQuery,
			Pageable pageable) {
		throw new UnsupportedOperationException();
	}

	private DataResponse loadOrgaPerson(DataRequest dataRequest)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		String personNumber = dataRequest.getEntityKey();
		CashReceipt cashReceipt = cashReceiptService
				.findByReceiptNumber(personNumber);
		DataView dataView = dataRequest.getDataView();
		DataResponse dataResponse = new DataResponse();
		dataResponse.setEntityKey(personNumber);
		dataResponse.setEntityName(dataRequest.getEntityName());
		ObjectMapper objectMapper = new ObjectMapper(dataView);
		dataResponse.getEntityData().putAll(objectMapper.toMap(cashReceipt));
		return dataResponse;
	}

	private DataResponse getResponseError(final Exception e) {
		DataResponse dataResponse = new DataResponse();
		dataResponse.setResultCode(DataResponse.RESULT_CODE_ERROR);
		dataResponse.setResultDetail(e.getMessage());
		return dataResponse;
	}
}
